package com.uucrazy.datacneter.m.sae.client.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpClientHelper
{
	// // http://uucrazy.sinaapp.com/getFiles.php?path=a
	// private static String WWW_SITE = "http://uucrazy.sinaapp.com";
	// private static String WEB_I_GETFILES = "getFiles.php";
	// private static String IMAGE_PATH_ROOT = "images";
	
	private static HttpClient httpclient = new DefaultHttpClient();

	//
	// /**
	// * 读取服务器目录下的数据
	// */
	// public String getPathFiles(String path) throws ClientProtocolException,
	// IOException {
	// Map<String, String> params = new HashMap<String, String>();
	// params.put("path", IMAGE_PATH_ROOT + "/" + path);
	// return getString(WWW_SITE + "/" + WEB_I_GETFILES, params);
	// }
	//	
	
	/**
	 * 取得图片的数据流
	 */
	public static InputStream  getInputStream(String path) throws ClientProtocolException, IOException
	{
		HttpGet httpget = new HttpGet(path);
		HttpResponse response;
		response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		return entity.getContent();
	}

	/**
	 * 通过URL取得 HttpGet中返回的结果
	 */
	public String getString(String url, Map<String, String> params) throws ClientProtocolException, IOException
	{
		String rs = null;
		StringBuffer paramUrl = new StringBuffer();
		if (url.indexOf('?') < 0)
		{
			paramUrl.append("?");
		}
		else
		{
			paramUrl.append("&");
		}

		// 参数构建
		Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
		while (iterator.hasNext())
		{
			Map.Entry<String, String> entry = iterator.next();
			paramUrl.append(entry.getKey());
			paramUrl.append("=");
			paramUrl.append(entry.getValue());
			paramUrl.append("&");
		}
		paramUrl.append("1=1");
		System.out.println(url + paramUrl.toString());
		// 请求
		HttpGet httpget = new HttpGet(url + paramUrl.toString());
		HttpResponse response;
		response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		if (entity != null)
		{
			long len = entity.getContentLength();
			if (len != -1 && len < 2048)
			{
				rs = EntityUtils.toString(entity);
			}
			else
			{
				InputStream instream = entity.getContent();
				int l = -1;
				StringBuffer sb = new StringBuffer();
				byte[] tmp = new byte[2048];
				while ((l = instream.read(tmp)) != -1)
				{
					sb.append(new String(tmp, 0, l));
				}
				rs = sb.toString();
			}
		}
		return rs;
	}

}
